<template>
  <el-dialog
    v-model="dialogVisible"
    title="批量操作"
    width="600px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
    >
      <el-form-item label="选中数量">
        <el-tag type="info">已选中 {{ selectedIds.length }} 条公告</el-tag>
      </el-form-item>

      <el-form-item label="操作类型" prop="operation">
        <el-select
          v-model="formData.operation"
          placeholder="请选择操作类型"
          style="width: 100%"
          @change="handleOperationChange"
        >
          <el-option
            v-for="option in utils.getBatchOperationOptions()"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item v-if="showOperationDescription" label="操作说明">
        <el-alert
          :title="operationDescription"
          :type="operationAlertType"
          show-icon
          :closable="false"
        />
      </el-form-item>

      <el-form-item v-if="showReasonInput" label="操作原因" prop="reason">
        <el-input
          v-model="formData.reason"
          type="textarea"
          placeholder="请输入操作原因（可选）"
          :rows="3"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button
          type="primary"
          :loading="submitLoading"
          @click="handleSubmit"
        >
          确定执行
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, nextTick } from "vue";
import {
  ElMessage,
  ElMessageBox,
  type FormInstance,
  type FormRules
} from "element-plus";
import {
  batchOperateAnnouncementsApi,
  AnnouncementManagementUtils,
  BatchOperationType,
  type BatchOperationRequest
} from "@/api/announcement-management";

// 将工具类暴露给模板
const utils = AnnouncementManagementUtils;

// Props
interface Props {
  visible: boolean;
  selectedIds: number[];
}

const props = withDefaults(defineProps<Props>(), {
  selectedIds: () => []
});

// Emits
const emit = defineEmits<{
  "update:visible": [value: boolean];
  success: [];
}>();

// 响应式数据
const formRef = ref<FormInstance>();
const submitLoading = ref(false);

// 计算属性
const dialogVisible = computed({
  get: () => props.visible,
  set: value => emit("update:visible", value)
});

// 表单数据
const formData = reactive<BatchOperationRequest>({
  announcementIds: [],
  operation: "",
  reason: ""
});

// 操作描述映射
const operationDescriptions = {
  [BatchOperationType.PUBLISH]: {
    text: "将选中的公告设置为已发布状态，用户将能够看到这些公告。",
    type: "success" as const
  },
  [BatchOperationType.ARCHIVE]: {
    text: "将选中的公告设置为已过期状态，用户将无法看到这些公告。",
    type: "warning" as const
  },
  [BatchOperationType.DELETE]: {
    text: "将选中的公告设置为已删除状态，这是软删除操作，数据不会丢失。",
    type: "danger" as const
  },
  [BatchOperationType.TOP]: {
    text: "将选中的公告设置为置顶状态，这些公告将显示在列表顶部。",
    type: "warning" as const
  },
  [BatchOperationType.UNTOP]: {
    text: "取消选中公告的置顶状态，这些公告将按正常顺序显示。",
    type: "info" as const
  },
  [BatchOperationType.POPUP]: {
    text: "将选中的公告设置为弹窗状态，用户登录时将弹窗显示这些公告。",
    type: "danger" as const
  },
  [BatchOperationType.UNPOPUP]: {
    text: "取消选中公告的弹窗状态，这些公告将不再弹窗显示。",
    type: "info" as const
  }
};

// 计算属性
const showOperationDescription = computed(() => {
  return formData.operation && operationDescriptions[formData.operation];
});

const operationDescription = computed(() => {
  return operationDescriptions[formData.operation]?.text || "";
});

const operationAlertType = computed(() => {
  return operationDescriptions[formData.operation]?.type || "info";
});

const showReasonInput = computed(() => {
  // 危险操作需要填写原因
  return [BatchOperationType.DELETE, BatchOperationType.ARCHIVE].includes(
    formData.operation as BatchOperationType
  );
});

// 表单验证规则
const formRules: FormRules = {
  operation: [{ required: true, message: "请选择操作类型", trigger: "change" }],
  reason: [
    {
      validator: (rule, value, callback) => {
        if (showReasonInput.value && !value?.trim()) {
          callback(new Error("请输入操作原因"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ]
};

// 操作类型变化处理
const handleOperationChange = () => {
  // 清空原因输入
  formData.reason = "";
  // 清除验证错误
  nextTick(() => {
    formRef.value?.clearValidate("reason");
  });
};

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    announcementIds: [],
    operation: "",
    reason: ""
  });
  nextTick(() => {
    formRef.value?.clearValidate();
  });
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();

    // 危险操作需要二次确认
    const isDangerousOperation = [
      BatchOperationType.DELETE,
      BatchOperationType.ARCHIVE
    ].includes(formData.operation as BatchOperationType);

    if (isDangerousOperation) {
      await ElMessageBox.confirm(
        `确定要对选中的 ${props.selectedIds.length} 条公告执行"${
          utils
            .getBatchOperationOptions()
            .find(op => op.value === formData.operation)?.label
        }"操作吗？`,
        "操作确认",
        {
          type: "warning",
          confirmButtonText: "确定",
          cancelButtonText: "取消"
        }
      );
    }

    submitLoading.value = true;

    // 设置公告ID列表
    formData.announcementIds = [...props.selectedIds];

    const response = await batchOperateAnnouncementsApi(formData);
    if (response && response.code === 200) {
      ElMessage.success("批量操作执行成功");
      emit("success");
    }
  } catch (error: any) {
    if (error !== "cancel") {
      console.error("批量操作失败:", error);
      ElMessage.error(`操作失败: ${error?.message || "未知错误"}`);
    }
  } finally {
    submitLoading.value = false;
  }
};

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false;
  resetForm();
};
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>
